<template>
    <edit-dialog :centerDialogVisible="visible" :tilte="title" :default-button="false" @Cancel="handleCancel" :width="width"
        class="addform">
        <template #content>
            <div>
                <el-form ref="maintenanceRef" :rules="rules" :model="addForm" label-width="110px" :inline="true">
                    <!-- 记录名称 :disabled="view" -->
                    <el-form-item label="记录名称:" prop="examineName">
                        <el-input placeholder="请输入记录名称" style="width: 230px" v-model="addForm.examineName" show-word-limit
                            v-if="!view"></el-input>
                        <el-text v-else class="mx-1" style="width: 230px" type="info">{{ addForm.examineName }}</el-text>
                    </el-form-item>

                    <!-- 单位名称 -->
                    <el-form-item label="单位名称:" prop="unitName">
                        <el-select v-model="addForm.unitName" style="width: 230px" placeholder="请选择单位名称" v-if="!view">
                            <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.label"
                                @click="changeUnitNumber(item.value)" />
                        </el-select>
                        <el-text v-else class="mx-1" style="width: 230px" type="info">{{ addForm.unitName }}</el-text>
                    </el-form-item>

                    <!-- 单位编号 -->
                    <el-form-item label="单位编号:" prop="unitNumber">
                        <el-input placeholder="请输入单位编号" style="width: 230px" v-model="addForm.unitNumber" disabled
                            v-if="!view" show-word-limit></el-input>
                        <el-text v-else class="mx-1" style="width: 230px" type="info">{{ addForm.unitNumber }}</el-text>
                    </el-form-item>

                    <!-- 检查人员 -->
                    <el-form-item label="检查人员:" prop="rummager">
                        <el-input placeholder="请输入检查人员" style="width: 230px" v-model="addForm.rummager" v-if="!view"
                            show-word-limit></el-input>
                        <el-text v-else class="mx-1" style="width: 230px" type="info">{{ addForm.rummager }}</el-text>
                    </el-form-item>

                    <!-- 检查日期 -->
                    <el-form-item label="检查日期:" prop="rummagerTime">
                        <el-date-picker v-model="addForm.rummagerTime" type="date" style="width: 230px" v-if="!view"
                            placeholder="检查日期" @change="time" />
                        <el-text v-else class="mx-1" style="width: 230px" type="info">
                            {{ addForm.rummagerTime != null || addForm.rummagerTime != undefined ?
                                addForm.rummagerTime.split('T')[0] : '' }}
                        </el-text>
                    </el-form-item>

                    <!-- 责任人 -->
                    <el-form-item label="责任人:" prop="dutyPerson">
                        <el-input placeholder="请输入责任人" style="width: 230px" v-model="addForm.dutyPerson" show-word-limit
                            v-if="!view"></el-input>
                        <el-text v-else class="mx-1" style="width: 230px" type="info">{{ addForm.dutyPerson }}</el-text>
                    </el-form-item>

                    <!-- 检查结果 -->
                    <el-form-item label="检查结果:" prop="inspectionResult">
                        <el-input placeholder="请输入检查结果" style="width: 975px" v-model="addForm.inspectionResult"
                            show-word-limit v-if="!view"></el-input>
                        <el-text v-else class="mx-1" style="width: 975px" type="info">
                            {{ addForm.inspectionResult }}
                        </el-text>
                    </el-form-item>

                    <!-- 存在问题 -->
                    <el-form-item label="存在问题:" prop="issue">
                        <el-input placeholder="请输入存在问题" style="width: 975px" v-model="addForm.issue" show-word-limit
                            v-if="!view">
                        </el-input>
                        <el-text v-else class="mx-1" style="width:975px" type="info">{{ addForm.issue }}</el-text>
                    </el-form-item>

                    <!-- 是否正常 -->
                    <el-form-item label="是否正常:" prop="isNormal">
                        <div class="my-4 flex items-center text-sm" v-if="!view">
                            <el-radio-group class="ml-4" v-model="addForm.isNormal" @change="clickExamine">
                                <el-radio :label=1>是</el-radio>
                                <el-radio :label=2>否</el-radio>
                            </el-radio-group>
                        </div>
                        <el-text v-else class="mx-1" style="width: 100px" type="info">
                            <span v-if="addForm.isNormal == 1">{{ '是' }}</span>
                            <span v-else-if="addForm.isNormal == 2">{{ '否' }}</span>
                        </el-text>
                    </el-form-item>

                    <!-- 是否整改 -->
                    <el-form-item label="是否整改:" prop="isRectify" v-show="state1">
                        <div class="my-4 flex items-center text-sm">
                            <el-radio-group class="ml-4" v-model="addForm.isRectify" @change="changeRectify" v-if="!view">
                                <el-radio :label=1>是</el-radio>
                                <el-radio :label=2>否</el-radio>
                            </el-radio-group>
                            <el-text v-else class="mx-1" style="width: 130px" type="info">
                                <span v-if="addForm.isRectify == 1">{{ '是' }}</span>
                                <span v-else-if="addForm.isRectify == 2">{{ '否' }}</span>
                            </el-text>
                        </div>
                    </el-form-item>

                    <!-- 整改期限  -->
                    <el-form-item label="整改期限:" prop="rectifyTime" v-show="state2">
                        <el-date-picker v-model="addForm.rectifyTime" type="date" style="width: 230px" v-if="!view"
                            placeholder="整改期限" @change="time"/>
                        <el-text v-else class="mx-1" style="width: 230px" type="info">
                            {{ addForm.rectifyTime != null || addForm.rectifyTime != undefined ?
                                addForm.rectifyTime.split('T')[0] : '' }}
                        </el-text>
                    </el-form-item>

                    <!-- 整改要求 -->
                    <el-form-item label="整改要求:" prop="rectifyRequire" v-show="state2">
                        <el-input placeholder="请输入整改要求" style="width: 975px" v-model="addForm.rectifyRequire" v-if="!view"
                            show-word-limit></el-input>
                        <el-text v-else class="mx-1" style="width: 975px" type="info">{{ addForm.rectifyRequire }}</el-text>
                    </el-form-item>

                    <!-- 整改状态 -->
                    <el-form-item label="整改状态:" prop="rectifyState" v-show="state2">
                        <div class="my-4 flex items-center text-sm">
                            <el-radio-group class="ml-4" v-model="addForm.isRectify" v-if="!view">
                                <el-radio :label=1>整改</el-radio>
                                <el-radio :label=2>未整改</el-radio>
                            </el-radio-group>
                            <el-text v-else class="mx-1" style="width: 975px" type="info">
                                <span v-if="addForm.isRectify == 1">{{ '整改' }}</span>
                                <span v-else-if="addForm.isRectify == 2">{{ '未整改' }}</span>
                            </el-text>
                        </div>
                    </el-form-item>
                    <br />
                    <!-- 附件 -->
                    <el-form-item label="附件:" prop="file">
                        <HyUpload :file-list="addForm.files" :disabled="view" :fileId="addForm.fileId" @changeFileId="changeFileId"/>
                    </el-form-item>
                </el-form>
                <MapTable style="height: 714px; padding: 0px;margin: 0px;" :map-table-data="addForm.areaList"
                    @changMapTable="changMapTable">
                </MapTable>
                <el-input placeholder="整改区域" style="width: 975px" v-model="addForm.areaList" v-if="false"></el-input>
            </div>
        </template>
        <template #custom>
            <span class="dialog-footer">
                <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
                <el-button type="primary" class="btn-ok" @click="handleAddSubmit(maintenanceRef)"
                    :disabled="view">确定</el-button>
            </span>
        </template>
    </edit-dialog>
</template>

<script setup lang="ts">
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage, dayjs } from 'element-plus';
import { reactive, ref, watch ,provide} from 'vue';
import HyUpload from "./components/HyUpload.vue";
import MapTable from './mapTable.vue';
import { addExamineInfo, securityUnitList,bind,insertExamineInfo } from "@/api/secure/examineInfo";
import { defineProps} from 'vue';
import { baseUrlConfig } from '@/config/config'
import { mapOptions } from '../cultivateRecycle/config/filters';
const businessBaseUrl = baseUrlConfig.businessBaseUrl

const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: ''
    },
    sonData: {
        type: Object,
        defult: () => { }
    },
    view: {
        type: String,
        defule: false
    }
})
// //文件id
// const changeFileId = (newId)=>{
//   addForm.fileId = newId
// }
provide('changeFileId',changeFileId)
const maintenanceRef = ref()
const state1 = ref(false);
const state2 = ref(false);

const width = ref('1160px');

let options = reactive([])

const emit = defineEmits(['cancel']);
watch(() => props.sonData, (newValue: any, oldValue: any) => {
    console.log('new');
    
    console.log(newValue);
    
    let files: any = [];
    if (newValue.enclosureCode != '' && newValue.resourceAddress != undefined) {
        files.push({
            enclosureCode: newValue.enclosureCode,
            enclosureContent: newValue.enclosureName + '.' + newValue.enclosureSuffix,
            enclosureName: newValue.enclosureName,
            enclosureSuffix: newValue.enclosureSuffix,
            resourceAddress: businessBaseUrl + newValue.resourceAddress,
        })
    }

    addForm.files = files;
    addForm.id = newValue.safetyInspeId;
    addForm.examineName = newValue.recordName;
    addForm.unitName = newValue.unitName;
    addForm.unitNumber = newValue.unitNumber;
    addForm.rummager = newValue.inspected;
    addForm.rummagerTime = newValue.inspectionTime;
    addForm.dutyPerson = newValue.personRespo;
    addForm.inspectionResult = newValue.inspectionResults;
    addForm.issue = newValue.sproblem;
    addForm.isNormal = newValue.normal
    clickExamine();

    addForm.isRectify = newValue.rectification;
    changeRectify();

    addForm.rectifyRequire = newValue.requirement;
    addForm.rectifyTime = newValue.limTime;
    addForm.rectifyState = newValue.rectifyState;

    addForm.areaList = newValue.areaList;
}, {
    deep: true,
})

watch(() => props.title, (newValue: any, oldValue: any) => {
    if (newValue == '新增' || newValue == '编辑') {
        getUnitList();

    }
}, {
    deep: true,
})

const changMapTable = (data: any) => {
    console.log('changMapTable', data);
    addForm.areaList = data;
}

//格式化时间
const time = () => {
    addForm.rummagerTime = dayjs(addForm.rummagerTime).format('YYYY-MM-DD');
}

// 单位编码
const changeUnitNumber = (obj: any) => {
    addForm.unitNumber = obj
}

// 判断正常按钮值状态
const clickExamine = () => {
    addForm.isNormal == '1' ? state1.value = true : state1.value = false;
}
// 判断整改按钮值状态
const changeRectify = () => {
    addForm.isRectify == '1' ? state2.value = true : state2.value = false;
}

const changeFileId = (value) => {
  addForm.fileId = value
}
//清空绑定值
const handleCancel = () => {
    addForm.id = null,
        addForm.examineName = '',
        addForm.unitName = '',
        addForm.unitNumber = '',
        addForm.rummager = '',
        addForm.rummagerTime = '',
        addForm.dutyPerson = '',
        addForm.inspectionResult = '',
        addForm.issue = '',
        addForm.isNormal = '0',
        addForm.isRectify = '',
        addForm.rectifyTime = '',
        addForm.rectifyRequire = '',
        addForm.repName = '',
        addForm.rectifyState = '',
        addForm.file = '',
        addForm.files = [],
        options = [],
        addForm.areaList = []

    state1.value = false;
    state2.value = false;
    emit('cancel')
}

let addForm = reactive({
    id: null,
    examineName: undefined,
    unitName: undefined,
    unitNumber: undefined,
    rummager: undefined,
    rummagerTime: undefined,
    dutyPerson: undefined,
    inspectionResult: undefined,
    issue: undefined,
    isNormal: '0',
    isRectify: undefined,
    rectifyTime: undefined,
    rectifyRequire: undefined,
    repName: undefined,
    rectifyState: undefined,
    file: undefined,
    files: [],
    areaList: [],
    fileId:''
    // 登录信息
    // creator: {
    //     id: '',
    //     name: '',
    //     organId: '',
    //     organName: '',
    //     phone: '',
    // }
})

const rules = reactive({
    examineName: [
        { required: true, message: '请输入记录名称', trigger: 'blur' },
    ],
    unitName: [
        { required: true, message: '请选择单位名称', trigger: 'change' },
    ],
    rummager: [
        { required: true, message: '请输入检查人', trigger: 'blur' },
    ]
})

const handleAddSubmit = async (formEl: any) => {
    if (addForm.files.length > 0) {
        addForm.file = addForm.files[0].enclosureCode;
    }
    if (!formEl) {
        return
    }
    await formEl.validate(async (valid: any) => {
        const data = ref({})
        if (valid) {
            data.value.safetyInspeId = addForm?.id
            data.value.recordName = addForm?.examineName
            data.value.unitName = addForm?.unitName
            data.value.inspected = addForm?.rummager
            data.value.inspectionTime = addForm.rummagerTime&&addForm.rummagerTime!='Invalid Date'?addForm.rummagerTime+' '+'00:00:00':undefined
            data.value.personRespo = addForm?.dutyPerson
            data.value.inspectionResults = addForm?.inspectionResult
            data.value.sproblem = addForm?.issue
            data.value.normal = addForm?.isNormal
            data.value.rectification = addForm?.isRectify
            console.log(addForm?.isRectify);
            console.log( data.value.rectification);
            
            data.value.requirement = addForm?.rectifyRequire
            if(addForm.rectifyTime instanceof Date){
                addForm.rectifyTime= new Date(addForm.rectifyTime.getTime()+24*60*60*1000)
            data.value.limTime = addForm.rectifyTime&&addForm.rectifyTime!='Invalid Date'?addForm.rectifyTime.toISOString().split('T')[0]+' 00:00:00':undefined
            } else{
                addForm.rectifyTime&&addForm.rectifyTime!='Invalid Date'?addForm.rectifyTime+' '+'00:00:00':undefined
            }
           
            data.value.entRecBin = '1' 
            data.value.unitNumber = addForm.unitNumber
            console.log(data);
            console.log(addForm);
            if(addForm.id == null || addForm.id == ''){
                addExamineInfo(data.value).then(res => {
                    ElMessage.success('添加成功');
                    data.value.safetyInspeId = res.safetyInspeId
                    data.value.fileId = addForm.fileId
                    console.log(addForm);
                    bind(data.value)
                handleCancel();
                emit('cancel')
            })
            }else{
                insertExamineInfo(data.value).then(res=>{
                        ElMessage.success('修改成功');
                        handleCancel();
                        emit('cancel')
                    })
            }
        }
    })


}
const getFile = ()=>{
    
}
// 获取外部单位数据
const getUnitList = () => {
    securityUnitList().then(res => {
        console.log(res);
        
        let data = res.map(item => {
            return {
                label: item.departName,
                value: item.id
            }
        })
        options = data
        console.log(mapOptions);
        console.log(addForm);
        
        
    })
}
</script>

<style scoped></style>
